﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table=FCNS.Data.Table;
using DoubleH.Utility;
using System.Windows.Interop;
using DoubleH.Utility.Configuration;
using System.Diagnostics;
using POS.Plugins;
using FCNS.Data;

namespace POS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
           
            InitUI();
            InitPosNO();
            InitDateTime();
            InitEvent();
            InitTemplete();
            LoadTemplete();
        }

        #region 变量属性
        ILoginTemplete pLogin = null;
        public IPayTemplete pPay = null;
        public ISaleTemplete pSale = null;
        #endregion
        //登录
        private bool CheckJiaoBan(Table.UserS selectedUser)
        {
            //检查交班状态
            App.CurrentShift = Table.PosShiftS.GetObjectNotShift(DoubleHConfig.AppConfig.PosNO);
            Table.UserS user = selectedUser;
            if (App.SaleMode)
            {
                if (App.CurrentShift == null)
                {
                    JiaoBanWindow jb = new JiaoBanWindow();
                    jb.Init(true, false);
                    jb.ShowDialog();
                    if (!jb.Ensure)
                        return false;

                    Table.PosShiftS pss = new Table.PosShiftS();
                    pss.PosNO = DoubleHConfig.AppConfig.PosNO;
                    pss.UserSId = user.Id;
                    pss.StartDateTime = DateTime.Now;
                    pss.StartMoney = jb.doubleUpDownMoney.Value.Value;
                    pss.Insert();
                    App.CurrentShift = pss;
                }
                else
                {
                    if (user.Id != App.CurrentShift.UserSId)
                        if (MessageWindow.Show("", App.CurrentShift._UserSName + " 尚未交班,是否继续?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                            return false;
                }
            }
            return true;
        }

        private void ShowSalePage()
        {
            //以下内容必须放这里,因为如果用户没登陆,初始化DataGridColumns就会出错,它是调去用户配置文件的.
            DoubleHConfig.UserConfig = ConfigSerializer.LoadUserConfig(Table.UserS.LoginUser.Id);
            labelUserName.Content = Table.UserS.LoginUser.Name;
            pSale.Init();
            ChangeUI(MainWindow.EnumUI.零售);
        }

        //销售
        //支付
        private void InitTemplete()
        {
            DefaultPluginHost pluginDefaultHost = new DefaultPluginHost();
            pluginDefaultHost.Initialize();
            App.PluginManager.Initialize(pluginDefaultHost);
            App.PluginManager.LoadAllExtension();
            PluginInfo success = App.PluginManager.Plugins.Find(f => f.Name == DoubleHConfig.AppConfig.PosMode);
            if (success == null)
            {
                pLogin = new StoreTemplete.PageLogin();
                pSale = new StoreTemplete.PageSale();
                pPay = new StoreTemplete.PagePay();
            }
            else
            {
                if (success.Interface.LoginPage() == null)
                    pLogin = new StoreTemplete.PageLogin();
                else
                    pLogin = success.Interface.LoginPage();

                if (success.Interface.SalePage() == null)
                    pSale = new StoreTemplete.PageSale();
                else
                    pSale = success.Interface.SalePage();

                if (success.Interface.PayPage() == null)
                    pPay = new StoreTemplete.PagePay();
                else
                    pPay = success.Interface.PayPage();
            }
        }

        private void LoadTemplete()
        {
            Debug.Assert(pLogin != null);
            Debug.Assert(pSale != null);
            Debug.Assert(pPay != null);

            pLogin.Logined += (ss) =>
            {
                Debug.Assert(ss != null);

                if (CheckJiaoBan(ss))
                {
                    Table.UserS.LoginUser = ss;
                    ShowSalePage();
                    Table.ErrorS.WriteLogFile(ss._LoginName + " 登陆成功");
                    App.Pos.UpdateLastLoginDateTime(DateTime.Now);
                }
                else
                    MessageWindow.Show("请先交班");
            };

            pPay.Payed += (ss) =>{Pay();};

            frame1.Navigate(pLogin);
        }

        private void InitUI()
        {
            if (DoubleHConfig.AppConfig.PosFullScreen)
            {
                this.WindowStyle = WindowStyle.None;
                this.WindowState = WindowState.Maximized;
            }
            else
            {
                this.WindowStyle = WindowStyle.ThreeDBorderWindow;
                this.WindowStartupLocation = WindowStartupLocation.Manual;
                this.WindowState = WindowState.Normal;
                this.Top = DoubleHConfig.AppConfig.PosTop;
                this.Left = DoubleHConfig.AppConfig.PosLeft;
                this.Width = DoubleHConfig.AppConfig.PosWidth;
                this.Height = DoubleHConfig.AppConfig.PosHeight;
            }

            this.Background = App.BackgroundBrush;
            this.Foreground = App.ForegroundBrush;
            this.FontSize = DoubleHConfig.AppConfig.PosFontSize;
            foreach (UIElement ui in mainGrid.Children)
            {
                Control c = ui as Control;
                if (c != null)
                {
                    c.Background = App.BackgroundBrush;
                    c.Foreground = App.ForegroundBrush;
                    c.FontSize = DoubleHConfig.AppConfig.PosFontSize;
                }
            }
        }

        private void InitPosNO()
        {
            //机器号
            App.Pos = Table.PosS.GetObject(DoubleHConfig.AppConfig.PosNO);
            string posName = System.Net.Dns.GetHostName();
            if (App.Pos == null || App.Pos.Id == -1 || posName != App.Pos.PosName)
            {
                PosNOconfig pn = new PosNOconfig(App.Pos);
                pn.ShowDialog();
                App.Pos = pn.Order;
            }
            if (App.Pos == null || App.Pos.Id == -1 || posName != App.Pos.PosName)
            {
                MessageWindow.Show("无法识别的POS端");
                this.Close();
            }

            App.ForceJiaoBan = DoubleHConfig.AppConfig.PosJiaoBan.Split(';');
            labelPosNO.Content += DoubleHConfig.AppConfig.PosNO;
            FCNS.Data.DbDefine.currentStoreSId = App.Pos.StoreSId;
            this.Title = FCNS.Data.DbDefine.SystemName;
            Table.ErrorS.WriteLogFile("加载POS系统");
        }

        private void InitDateTime()
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Interval = 1000;
            t.Tick += (ss, ee) =>
            {
                labelDateTime.Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //ForceJiaoBan();
            };

            t.Start();
        }
        /// <summary>
        /// 强制交班,仅能 InitDateTime 调用
        /// </summary>
        private void ForceJiaoBan()
        {
            if (App.ForceJiaoBan.Length == 0)
                return;
            if (!App.ForceJiaoBan.Contains(DateTime.Now.ToString("HHmm")))
                return;
            if (!App.SaleMode || Table.UserS.LoginUser == null)
                return;

            App.SaleMode = false;//因为是按秒验证的,防止不断的弹出交班窗体后
            JiaoBanWindow jb = new JiaoBanWindow();
            jb.Init(false, true);
            jb.ShowDialog();
            if (DoubleHConfig.AppConfig.PosIsPrintJiaoBan)
                PrintFunction.PrintPosJiaoBan(Table.UserS.LoginUser._LoginName, App.CurrentShift.PosNO, jb.doubleUpDownMoney.Value.Value.ToString(), jb.labelMoneySum.Content.ToString());

            LogOff(false);
        }

        private void InitEvent()
        {
            this.Closing += (ss, ee) =>
            {
                IntPtr handle = new WindowInteropHelper(this).Handle;
                WindowsUtility.UnregisterHotKey(handle, 0x9900);
                if (MessageWindow.Show("", "是否要关闭POS系统", MessageBoxButton.YesNo) == MessageBoxResult.No)
                {
                    WindowsUtility.RegisterHotKey(handle, 0x9900, System.Windows.Forms.Keys.Escape);
                    ee.Cancel = true;
                    return;
                }

                Table.ErrorS.WriteLogFile("关闭POS系统");
                if (!DoubleHConfig.AppConfig.PosFullScreen)
                {
                    DoubleHConfig.AppConfig.PosLeft = this.Left;
                    DoubleHConfig.AppConfig.PosTop = this.Top;
                    DoubleHConfig.AppConfig.PosWidth = this.Width;
                    DoubleHConfig.AppConfig.PosHeight = this.Height;
                }
                ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, DbDefine.appConfigFile);
                UnInitKeyDown();
            };
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            InitKeyDown();
        }

        IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handle)
        {
            KeyDowned(wParam.ToInt32());
            //Debug.WriteLine("hwnd:{0},msg:{1},wParam:{2},lParam{3}:,handle:{4}"
            //                ,hwnd,msg,wParam,lParam,handle);
            //if (wParam.ToInt32() == 0x9999)
            //{
            //    MessageBox.Show("dfd");
            //全局快捷键要执行的命令
            //}
            return IntPtr.Zero;
        }

       /// <summary>
       /// 结账并打印
       /// </summary>
        public void Pay()
        {
            if (App.SaleMode)
            {
                App.Order.PosNO = App.Pos.PosNO;
                App.Order.StoreSId = App.Pos.StoreSId;
                Table.DataTableS.EnumDatabaseStatus result = App.Order.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    DoubleHConfig.AppConfig.PosCashboxMoney += App.Order.Money;
                else
                    MessageWindow.Show(result.ToString());
            }

            if (DoubleHConfig.AppConfig.PosIsPrint)
            {
                PrintFunction.PrintPosOrder(App.Order);
            }

            App.MWindow.ChangeUI(MainWindow.EnumUI.零售);
        }
    }
}